import { useState, ReactNode, useEffect } from "react";
import { createPortal } from "react-dom";

interface ShowPopupProps {
    content: ReactNode;
    position: { left: number; top: number } | null;
    onClose: () => void;
}

export const ShowPopup = ({ content, position, onClose }: ShowPopupProps) => {
    if (!position) return null;

    return createPortal(
        <div
            className="absolute bg-white border border-gray-300 shadow-lg p-3 rounded-lg"
            style={{ left: position.left, top: position.top, position: "absolute", zIndex: 1000 }}
            onClick={(e) => e.stopPropagation()} // 防止冒泡
        >
            {content}
            <button onClick={onClose} className="mt-2 text-sm text-red-500">
                关闭
            </button>
        </div>,
        document.body
    );
};

export const poupp = (e: React.MouseEvent, jsx: string) => {
    // 获取点击元素的位置和尺寸
    const spanElement = e.target as HTMLElement;
    const spanRect = spanElement.getBoundingClientRect();

    // 创建弹窗元素
    const popup = document.createElement('div');
    popup.innerHTML = jsx; // 使用 innerHTML 插入 <div>

    // 设置弹窗样式
    popup.style.position = 'absolute';
    popup.style.left = `${spanRect.left}px`;
    popup.style.top = `${spanRect.bottom + window.scrollY}px`;
    popup.style.backgroundColor = 'white';
    // popup.style.border = '1px solid #ccc';
    popup.style.padding = '0px';
    popup.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.1)';
    popup.style.zIndex = '1000';

    // 将弹窗添加到 body 中
    document.body.appendChild(popup);

    // 添加点击事件监听器，点击弹窗外部区域时关闭弹窗
    const closePopup = (e: MouseEvent) => {
        if (!popup.contains(e.target as Node)) { // 判断是否点击在弹窗外部区域
            popup.remove();
            document.removeEventListener('click', closePopup);
        }
    };
    document.addEventListener('click', closePopup);

}